package com.dly.hope.utils;

import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @author linyu.dai
 * @project myserve
 * @description 注解工具类
 * @creat 2022/8/29 21:37:11
 */
public class CommonUtil {

    /**
     * @Author linyu.dai
     * @Description 从方法类上找注解 找不到就去声明类上找
     * @Date 2022/8/29 21:44
     * @Param [handlerMethod, annotationClass]
     * @return A
     */
    public static <A> A getAnnotation(HandlerMethod handlerMethod, Class<? extends Annotation> annotationClass){
        A annotation = null;
        //获取方法
        Method method = handlerMethod.getMethod();
        //判断是否存在该注解
        if(method.isAnnotationPresent(annotationClass)){
            annotation = (A) method.getAnnotation(annotationClass);
        }else{
            //从声明类找
            Class<?> beanType = handlerMethod.getBean().getClass();
            if(beanType.isAnnotationPresent(annotationClass)){
                annotation = (A) beanType.getAnnotation(annotationClass);
            }
        }
        return annotation;
    }

    /**
     * @Author linyu.dai
     * @Description 从参数或者头中获取token
     * @Date 2022/8/29 21:58
     * @Param [request, jwtHeader]
     * @return java.lang.String
     */
    public static  String getToken(HttpServletRequest request, String jwtHeader){
        //重请求头里获取token
        String token = request.getHeader(jwtHeader);
        //如果不存在重参数里面获取
        if(Objects.isNull(token)){
            token = request.getParameter(jwtHeader);
        }
        return token;
    }
}
